package com.yaowk.email.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.JMap;
import com.yaowk.authc.model.Platform;
import com.yaowk.authc.model.User;
import com.yaowk.common.kit.ResultKit;
import com.yaowk.common.validator.RequiredIdValidator;
import com.yaowk.system.model.Module;
import com.yaowk.system.model.ModulePlatform;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户列表
 *
 * @authc yaowk
 * 2017/5/11
 */
public class UserController extends Controller {

    /**
     * 通过平台id查询发送人
     *
     * @param id|平台id|Integer|必填
     * @title 通过平台id查询发送人
     */
    @Before(RequiredIdValidator.class)
    @RequiresPermissions("filePush:read")
    public void list() {
        List<JMap> result = new ArrayList<>();

        // 查询该平台的用户
        Integer platformId = getParaToInt("id");
        searchUserByPlatformId(result, platformId);

        // 查询管理模块的用户
        Module module = Module.dao.findByPlatFormIdAndSign(platformId, "filePush");
        List<ModulePlatform> modulePlatformList = ModulePlatform.dao.findByModuleId(module.getId());
        for (ModulePlatform modulePlatform : modulePlatformList) {
            searchUserByPlatformId(result, modulePlatform.getPlatformId());
        }

        renderJson(ResultKit.success(result));
    }

    /**
     * 通过模块id查询对应用户
     */
    private void searchUserByPlatformId(List<JMap> result, Integer platformId) {

        Platform platform = Platform.dao.findById(platformId);
        List<User> userList = User.dao.findByPlatformIdAndType(platformId, null);
        List<JMap> jMapList = new ArrayList<>();
        for (User user : userList) {
            jMapList.add(JMap.create().set("id", user.getId()).set("name", user.getName()).set("user_code", user.getUserCode()));
        }
        result.add(JMap.create().set("name", platform.getName()).set("users", jMapList));

    }
}
